/**
 * @description 企业用户管理
 * @author 李艳
 */
import React, { Component } from "react";
import { listAllCanAssignEmployeesIncludeSubNode, savePosition } from "./EnterpriseUserService";
import { Input, Button, Checkbox, Col, Form, message, Row } from "antd";
import SimpleTable from "../../../commons/components/SimpleTable";
import { hide, show } from "../../../configs/SharedReducer";
import connect from "react-redux/es/connect/connect";
import EnterpriseUserConfigTabsView from "./EnterpriseUserConfigTabsView";
import { listAllTree } from "../Organization/OrganizationService";
import EditEnterpriseUserModal from "./EditEnterpriseUserModal";
import { defaultPageSize, rowGutter } from "../../../configs/DefaultConfig";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import DetailCard from "../../../commons/components/DetailCard";
import StandardTree from "../../../commons/components/StandardTree";
import PageOperateHoc from "../../../commons/components/PageOperateHoc/index.jsx";
import CheckAuth from '../../../commons/components/CheckAuth';
const Search = Input.Search;

class EnterpriseUserView extends Component {
  constructor(props) {
    super(props);
    this.initPath = [{ name: "企业用户管理" }]
    this.state = {
      treeData: [],
      searchValue: "",
      tableSearchValue: "",
      tableData: [],
      findResultData: [],
      autoExpandParent: true,
      expandedKeys: [],
      treeSelectedKeys: [],
      selectedNode: {},
      loading: false,
      tableSelectRow: [],
      modalVisible: false,
      confirmLoading: false,
      isAdd: true,
      pathName: "详细信息",
      scrollY: null,
      includeSubNode: false,
      isPositionConfig: false,
      pageInfo: { page: 1, rows: defaultPageSize }
    }
  }

  onModalRef = (ref) => {
    this.modalRef = ref;
  };

  componentWillMount() {
    this.getTreeData()
  };

  //网络请求树控件数据
  getTreeData = (param) => {
    this.props.show();
    listAllTree(param).then((result) => {
      this.setState({
        treeData: result,
      });
    }).catch(err => {
    }).finally(() => {
      this.props.hide();
    });
  };

  //网络请求table控件数据
  listAllCanAssignEmployeesIncludeSubNode = (param) => {
    this.setState({ loading: true });
    listAllCanAssignEmployeesIncludeSubNode(param).then((result) => {
      this.setState({
        tableData: result, tableSelectRow: []
      });
    }).catch(err => {
    }).finally(() => {
      this.setState({ loading: false });
    });
  };

  //树节点选择触发
  onTreeSelect = (selectedKeys, selectedNodes) => {
    this.setState({ treeSelectedKeys: selectedKeys });
    this.setState({ selectedNode: selectedNodes[0] });
    let params = {
      pageInfo: this.state.pageInfo,
      organizationId: selectedKeys[0],
      includeSubNode: this.state.includeSubNode
    };
    this.listAllCanAssignEmployeesIncludeSubNode(params);
    this.setState({ pathName: selectedNodes[0].name ? selectedNodes[0].name : '岗位' });
  };

  handleTableSearch = (value) => {
    if (this.state.selectedNode.id) {
      this.setState({ tableSearchValue: value });
      let params = {
        quickSearchValue: value,
        pageInfo: this.state.pageInfo,
        organizationId: this.state.selectedNode.id,
        includeSubNode: this.state.includeSubNode
      };
      this.listAllCanAssignEmployeesIncludeSubNode(params)
    }
  };
  onAddRuleClick = () => {
    if (this.state.selectedNode && JSON.stringify(this.state.selectedNode) !== "{}") {
      this.setState({
        modalVisible: true,
        isAdd: true
      })
    } else {
      message.error('请选择组织机构')
    }

  };
  onEditPositionClick = (record) => {
    this.setState({ rightEditData: record })
    this.setState({
      modalVisible: true,
      isAdd: false
    })
  };
  //新增或编辑点击确定按钮事件
  handleEditPosition = () => {
    //表单数据同步
    if (this.modalRef && this.modalRef.props.form) {
      this.modalRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          //如果表单验证通过，则进行网络请求保存更改或新增的数据
          this.setState({ confirmLoading: true, modalVisible: true });
          if (this.state.isAdd) {
            delete values.id
          }
          savePosition(values).then((result) => {
            if (result.status === "SUCCESS") {
              message.success(result.message ? result.message : "保存成功");
              //请求table数据刷新本地数据
              let params = {
                quickSearchValue: this.state.tableSearchValue,
                organizationId: this.state.selectedNode.id,
                includeSubNode: this.state.includeSubNode
              };
              this.listAllCanAssignEmployeesIncludeSubNode(params);
              this.setState({ confirmLoading: false, modalVisible: false });
            } else {
              message.error(result.message ? result.message : "保存失败");
              this.setState({ confirmLoading: false });
            }
          }).catch(err => {
            this.setState({ confirmLoading: false });
          })
        }
      })
    }
  };

  handleModalCancel = () => {
    this.setState({ modalVisible: false })
  };

  onTableSelectRow = (tableSelectRow) => {
    this.setState({ tableSelectRow });
  };
  judgeSelected = () => {
    if (!this.state.tableSelectRow[0]) {
      message.error('请选择一行数据！');
      return false;
    }
    return true;
  };

  //是否包含子节点，params：selectedId,includeSubNode
  includeSubNode = (e) => {
    const {tableSearchValue,selectedNode}=this.state;
    this.setState({ includeSubNode: e.target.checked });
    //发送请求
    if (selectedNode&&selectedNode.id){
      let params = {
        quickSearchValue: tableSearchValue,
        organizationId: selectedNode.id,
        includeSubNode: e.target.checked
      };
      this.listAllCanAssignEmployeesIncludeSubNode(params);
    }
  };

  onPositionConfigClick = () => {
    if (!this.judgeSelected()) return;
    this.setDisplay(true)
  };

  setDisplay = (display) => {
    this.setState({ isPositionConfig: display })
  };
  pageChange = (pagination) => {
    let params = {
      quickSearchValue: this.state.tableSearchValue,
      pageInfo: pagination,
      organizationId: this.state.selectedNode.id,
      includeSubNode: this.state.includeSubNode
    };

    this.listAllCanAssignEmployeesIncludeSubNode(params)
  };
  getPathData = () => {
    const { isPositionConfig, tableSelectRow } = this.state;
    if (isPositionConfig) {
      const path = [{ name: "用户配置 " }, { name: `当前用户【${tableSelectRow[0].userName}】` }];
      return [...this.initPath, ...path];
    } else {
      return null;
    }
  }
  getExtra = () => {
    const { isPositionConfig } = this.state;
    if (isPositionConfig) {
      return [
        <Button key={"return"} onClick={() => this.setDisplay(false)}>返回</Button>
      ]
    }
    return null;
  }
  render() {
    const columns = [
      {
        title: "操作",
        width: 60,
        dataIndex: "operator",
        render: (text, record, index) => {
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <CheckAuth operateCode="BASIC-YHGL-ENTERPRISEUSER-EDIT">
                <a className={'row-operator-item'} onClick={() => this.onEditPositionClick(record)}>编辑</a>
              </CheckAuth>
            </div>
          )
        }
      },
      {
        title: '员工编号',
        dataIndex: 'code',
        width: 180
      },
      {
        title: '姓名',
        dataIndex: 'userName',
        width: 180
      },
      {
        title: '冻结',
        dataIndex: 'frozen',
        width: 180,
        render: (text, record) => {
          return <Checkbox checked={record.frozen === true} disabled />
        }
      }
    ];
    const title = () => {
      return [
        <CheckAuth operateCode="BASIC-YHGL-ENTERPRISEUSER-ADD" key="addRule">
          <Button  className={"primaryButton"} type={"primary"}
            onClick={this.onAddRuleClick}>新增</Button>
        </CheckAuth>,
        <CheckAuth operateCode="BASIC-YHGL-ENTERPRISEUSER-CONFIG" key="config" >
          <Button style={{ marginRight: 8 }}
            onClick={this.onPositionConfigClick}>配置</Button>
        </CheckAuth>,
        <span key="child">包含子节点：<Checkbox onChange={this.includeSubNode} /></span>

      ]
    };

    //表头搜索框
    const search = () => {
      return [
        <Search
          key="search"
          placeholder="输入员工编号或姓名查询"
          onSearch={value => this.handleTableSearch(value)}
          style={{ width: 220 }}
          allowClear
        />
      ]
    };
    const { isPositionConfig } = this.state;
    return (
      <HeadBreadcrumb
        style={isPositionConfig ? { margin: 0, padding: 0, height: "100%" } : { overflow: "hidden" }}
        pathData={this.getPathData()}
        rightExtra={this.getExtra()}
        className={isPositionConfig ? "" : "allocation-page"}
      >
        <Row gutter={rowGutter} style={{ height: "100%", display: this.state.isPositionConfig ? "none" : "block" }}>
          {/*左边的树状控件*/}
          <Col span={10} style={{ height: "100%" }}>
            <DetailCard
              title="组织机构"
              style={{ height: "100%" }}
              bodyStyle={{ height: "calc(100% - 53px)" }}
            >
              <StandardTree
                draggable={false}
                onSelect={this.onTreeSelect}
                dadaSource={this.state.treeData} />
            </DetailCard>

          </Col>
          {/*右边的表格控件*/}
          <Col span={14} style={{ height: "100%" }}>
            <DetailCard className={"child-card"} title={this.state.pathName} style={{ height: "100%" }}>
              <div className={'tbar-box'}>
                <div className={'tbar-btn-box'}>{title()}</div>
                <div className={'tbar-search-box'}>{search()}</div>
              </div>
              <SimpleTable
                inCard={true}
                data={this.state.tableData}
                columns={columns}
                loading={this.state.loading}
                onSelectRow={this.onTableSelectRow}
                rowsSelected={this.state.tableSelectRow}
                pageChange={this.pageChange}
              />
            </DetailCard>

            <EditEnterpriseUserModal
              modalVisible={this.state.modalVisible}
              confirmLoading={this.state.confirmLoading}
              handleOk={this.handleEditPosition}
              handleCancel={this.handleModalCancel}
              onRef={this.onModalRef}
              defaultValue={this.state.rightEditData ? this.state.rightEditData : {}}
              selectedNode={this.state.selectedNode}
              isAdd={this.state.isAdd}
            />
          </Col>
        </Row>
        {
          this.state.isPositionConfig ? <EnterpriseUserConfigTabsView
            userInfo={this.state.tableSelectRow[0] ? this.state.tableSelectRow[0] : {}}
          /> : null
        }
      </HeadBreadcrumb>
    )
  }
}

const mapStateToProps = (state) => {
  return {};
};

const mapDispatchToProps = (dispatch) => {
  return {
    show: () => {
      dispatch(show())
    },
    hide: () => {
      dispatch(hide())
    },
  }
};
EnterpriseUserView = Form.create()(EnterpriseUserView);
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageOperateHoc(EnterpriseUserView))
